package com.startx.http.dao.impl;

import java.util.Map;

import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import com.startx.http.dao.IDataEntryDao;
import com.startx.http.dao.MongodBaseDao;
import com.startx.http.entity.data.DataEntry;
import com.startx.http.system.constant.Constants;

@Repository
public class DataEntryDao extends MongodBaseDao<DataEntry> implements IDataEntryDao {

	@Override
	public void saveOrUpdate(DataEntry entry) {
		Query query = new Query(new Criteria("userId").is(entry.getUserId()));
		
		if(super.count(query) <= 0) {
			
			super.save(entry);
			
		} else {
			
			Update update = new Update();
			
			for (String key : entry.getEntry().keySet()) {
				update.set("entry."+key, entry.getEntry().get(key));
			}
			
			super.getMongoTemplate().updateFirst(query, update, DataEntry.class);
		}
	}

	@Override
	public Map<String,?> getKeyValueByKey(String userId, String key) {
		Query query = new Query(new Criteria("userId").is(userId));
		
		Map<String,?> data = Constants.EMPTY_DICTIONARY;
		if(super.count(query) > 0) {
			Criteria queryL = new Criteria("userId").is(userId);
			Criteria fieldL = new Criteria("entry."+key).is(1);
			query = new BasicQuery(queryL.getCriteriaObject(),fieldL.getCriteriaObject());
			data = super.list(query).get(0).getEntry();
		}	
		
		return data;
	}
	
}
